package com.roc.web.action.settlemgr;

import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.bean.FreezeBean;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.service.StrongDeductionsService;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;

@Component
@Namespace("/deductions")
@Scope("prototype")
public class StrongDeductionsAction extends PaginationBaseAction{
	
	private static Logger logger = Logger.getLogger(StrongDeductionsAction.class);
	
	@Autowired
	private IPageService pagenitionService;
	
	@Autowired
	private StrongDeductionsService strongDeductionsService;
	
	private StrongDeductionsSearchCondition searchCondition;
	
	private String deductionsMoney;
	private String keyStr;
	
	
	/**
	 * 初始化冻结商户页面
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "init", results = {
			@Result(name = "success", location = "/pages/settlement/strongDeductions.jsp"),
			@Result(name = "error", location = "/error.jsp") })
	public String init() throws Exception {
		Operators op = (Operators) getSession().getAttribute(
				Constant.SESSION_LOGIN_MERCHANT);
		if (op.getRoleType().equals(Role.CLEAR_OPERATORS.getCode())
				|| op.getRoleType().equals(Role.CLEAR_LEAD.getCode())
				|| op.getRoleType().equals(Role.SYSTEM.getCode())
				|| op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode())
				|| op.getRoleType().equals(
						Role.RISK_CONTROL_OPERATORS.getCode())) {
			return SUCCESS;
		}
		addActionError("无权限访问!!!");
		return ERROR;
	}
	
	/**
	 * 查询冻结商户页面
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "queryFreeze", results = {
			@Result(name = "success", location = "/pages/settlement/strongDeductions.jsp"),
			@Result(name = "error", location = "/error.jsp") })
	public String queryFreeze() throws Exception {
		try {
			if (searchCondition == null) {
				searchCondition = (StrongDeductionsSearchCondition) getSearchConditionFromSession();
				if (searchCondition == null) {
					searchCondition = new StrongDeductionsSearchCondition();
				}
			}
			int rows = pagenitionService.countSQL(searchCondition);

			if (rows > 0) {
				searchRsList = pagenitionService.findAllSQL(searchCondition,
						calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
				dealWithTheListSpecially(searchRsList);

				List<FreezeBean> list = new ArrayList<FreezeBean>();
				if (null != searchRsList && searchRsList.size() > 0) {
					Iterator<?> iterator = searchRsList.iterator();
					while (iterator.hasNext()) {
						Object[] obj = (Object[]) iterator.next();

//						DecimalFormat df = new DecimalFormat("#.##");// 数据库存的分，转成元保留小数点后两位
//						double freezeAmt = Double.parseDouble(Constance
//								.Null2EmptyTrim(obj[2]));
//						double freezeHadSum = Double.parseDouble(Constance
//								.Null2EmptyTrim(obj[3]));
//						double freezeWeiSum = Double.parseDouble(Constance
//								.Null2EmptyTrim(obj[4]));
						
						String freezeAmt = Constance.Null2EmptyTrim(obj[2]);
						String freezeHadSum = Constance.Null2EmptyTrim(obj[3]);
						String freezeWeiSum = Constance.Null2EmptyTrim(obj[4]);
						if("".equals(freezeAmt)){
							freezeAmt = "0.00";
						}
						if("".equals(freezeHadSum)){
							freezeHadSum = "0.00";
						}
						
						if("".equals(freezeWeiSum)){
							freezeWeiSum = "0.00";
						}
						

						FreezeBean fb = new FreezeBean();
						fb.setKeyStr(Long.parseLong(Constance
								.Null2EmptyTrim(obj[0])));
						fb.setMchntCd(Constance.Null2EmptyTrim(obj[1]));
						fb.setFreezeAmt(new BigDecimal(freezeAmt).divide(new BigDecimal(100)).toPlainString());//(df.format(freezeAmt / 100)).toString()
						fb.setFreezeHadSum(new BigDecimal(freezeHadSum).divide(new BigDecimal(100)).toPlainString());//(df.format(freezeHadSum / 100)).toString()
						fb.setFreezeWeiSum(new BigDecimal(freezeWeiSum).divide(new BigDecimal(100)).toPlainString());//(df.format(freezeWeiSum / 100)).toString()
						fb.setUseStatus(Constance.Null2EmptyTrim(obj[5]));
						fb.setFreezeFlag(Constance.Null2EmptyTrim(obj[6]));
						fb.setOldTransKey(Constance.Null2EmptyTrim(obj[7]));
						fb.setOldTransCardNo(Constance.Null2EmptyTrim(obj[8]));
						fb.setRecCrtTs(Constance.Null2EmptyTrim(obj[9]));
						fb.setRecUpdTs(Constance.Null2EmptyTrim(obj[10]));
						fb.setRemark(Constance.Null2EmptyTrim(obj[11]));
						fb.setOperator(Constance.Null2EmptyTrim(obj[12]));
						fb.setMchtName(Constance.Null2EmptyTrim(obj[13]));
						fb.setBranchCompy(Constance.Null2EmptyTrim(obj[14]));
						fb.setOneAgent(Constance.Null2EmptyTrim(obj[15]));
						fb.setDirectAgent(Constance.Null2EmptyTrim(obj[16]));
						String deductionsAmt = Constance.Null2EmptyTrim(obj[17]);
						if(!"".equals(deductionsAmt)){
							fb.setDeductionsAmt(new BigDecimal(deductionsAmt).divide(new BigDecimal(100)).toString());
						}else{
							fb.setDeductionsAmt("0.00");
						}
						fb.setCanDeductionAmt(new BigDecimal(fb.getFreezeHadSum()).subtract(new BigDecimal(fb.getDeductionsAmt())).toString());
						list.add(fb);
					}
					searchRsList.clear();
					searchRsList.addAll(list);

				}

			}
			if (searchRsList.size() == 0) {
				getRequest().setAttribute("msge", "查询冻结商户为空");
			}

			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
			return ERROR;
		}
		return SUCCESS;

	}
	
	
	/**
	 * 放款
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "deductionsMoney")
	public String deductionsMoney(){
		Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		HttpServletResponse response = ServletActionContext.getResponse();
	    response.setCharacterEncoding("UTF-8");
		JSONObject jsonObject = new JSONObject();
		PrintWriter out = null;
		Map<String,Object> resMap = null;
		try {
			out = response.getWriter();
			resMap = strongDeductionsService.modifyDecMoney(logingMerchant, keyStr, deductionsMoney);
			jsonObject.put("res", resMap);
			
		} catch (Exception e) {
			logger.error("强扣放款异常:{}",e);
			resMap = new HashMap<String, Object>();
			resMap.put("flag", false);
			resMap.put("msg", "强扣放款异常");
			jsonObject.put("res", resMap);
		}
		out.print(jsonObject.toString());
		out.flush();
		out.close();
		return null;
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
		
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_DEDUCTIONS_QUERY, searchCondition);
		
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return (BaseSearchCondition) getSession().getAttribute(
				SEARCH_SESSION_DEDUCTIONS_QUERY);
	}

	@Override
	protected String getInitPageSize() {
		return Constance.PAGE_MAX_SIZE + "";
	}

	public StrongDeductionsSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(StrongDeductionsSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public String getDeductionsMoney() {
		return deductionsMoney;
	}

	public void setDeductionsMoney(String deductionsMoney) {
		this.deductionsMoney = deductionsMoney;
	}

	public String getKeyStr() {
		return keyStr;
	}

	public void setKeyStr(String keyStr) {
		this.keyStr = keyStr;
	}
	
	
	
}
